<template>
	<view class="container">
		<!-- 详情区域 -->
		<view v-if="escortInfo" class="detail-container">
			<view class="weui-cell weui-cell_access" hover-class="weui-cell_active">
				<view class="weui-cell__bd">{{ escortInfo.name }}</view>
				<view class="weui-cell__ft weui-cell__ft_in-access">
					<button class="cancel-button" @click="cancelEscort(escortInfo.id)">撤销</button>
				</view>
			</view>
			<view class="detail-item">
				<label>性别:</label>
				<text>{{ sexOptions[escortInfo.sex].name }}</text>
			</view>
			<view class="detail-item">
				<label>年龄:</label>
				<text>{{ escortInfo.age }}</text>
			</view>
			<view class="detail-item">
				<label>手机号:</label>
				<text>{{ escortInfo.phone }}</text>
			</view>
			<view class="detail-item">
				<label>身份证号:</label>
				<text>{{ escortInfo.identityCard }}</text>
			</view>
			<view class="detail-item">
				<label>医院ID:</label>
				<text>{{ escortInfo.hospitalId }}</text>
			</view>
			<view class="detail-item">
				<label>地址信息:</label>
				<text>{{ escortInfo.addressInfo }}</text>
			</view>
			<view class="detail-item">
				<label>描述:</label>
				<text>{{ escortInfo.description }}</text>
			</view>
		</view>

		<!-- 固定底部申请按钮 -->
		<view class="fixed-bottom">
			<button class="apply-button" @tap="handleModal">申请</button>
		</view>

		<!-- 模态框 -->
		<view ref="popup" class="modal-overlay" v-show="showModal">
			<view class="modal-content">
				<form @submit.prevent="handleSubmit">
					<scroll-view scroll-y class="form-scroll">
						<view class="form-item">
							<label>姓名</label>
							<input v-model="formData.name" placeholder="请输入姓名" required />
						</view>
						<view class="form-item">
							<label>年龄</label>
							<input v-model="formData.age" placeholder="请输入年龄" required />
						</view>
						<view class="form-item">
							<label>性别</label>
							<picker mode="selector" :range="sexOptions" range-key="name" @change="handleSexChange">
								<view>{{ sexOptions[formData.sex].name }}</view>
							</picker>
						</view>
						<view class="form-item">
							<label>手机号</label>
							<input v-model="formData.phone" placeholder="请输入手机号" required />
						</view>
						<view class="form-item">
							<label>身份证号</label>
							<input v-model="formData.identityCard" placeholder="请输入身份证号" required />
						</view>
						<view class="form-item">
							<label>医院</label>
							<picker mode="selector" :range="myhospitals" range-key="hospitalName"
								@change="handleHospitalChange">
								<view>
									{{ myhospitals[formData.hospitalId] ? myhospitals[formData.hospitalId].hospitalName : '请选择医院' }}
								</view>
							</picker>
						</view>
						<view class="form-item">
							<label>地址信息</label>
							<textarea v-model="formData.addressInfo" placeholder="请输入地址信息" required></textarea>
						</view>
						<view class="form-item">
							<label>描述</label>
							<textarea v-model="formData.description" placeholder="请输入描述" required></textarea>
						</view>

						<!-- 头像上传 -->
						<view class="form-item">
							<label>头像</label>
							<button @click="chooseAvatar">选择头像</button>
							<image v-if="avatarUrl" :src="avatarUrl" style="width: 100px; height: 100px;" />
						</view>

						<!-- 个性化描述图片上传 -->
						<view class="form-item">
							<label>个性化描述图片</label>
							<button @click="chooseFiles">选择图片</button>
							<view v-for="(fileUrl, index) in filesUrls" :key="index">
								<image :src="fileUrl" style="width: 100px; height: 100px;" />
							</view>
						</view>
					</scroll-view>
					<view class="modal-footer">
						<button form-type="submit" class="submit-button">提交</button>
						<button class="cancel-button" @click="showModal = false">取消</button>
					</view>
				</form>
			</view>
		</view>
	</view>
</template>

<script setup>
	import {
		ref,
		onMounted
	} from 'vue';
	import {
		onLoad
	} from '@dcloudio/uni-app';
	import {
		myrequest
	} from '@/common/js/utils';

	const escortInfo = ref(null);
	const showModal = ref(false);
	const token = uni.getStorageSync('token');
	const formData = ref({
		name: '',
		age: '',
		sex: 0,
		phone: '',
		identityCard: '',
		hospitalId: '',
		addressInfo: '',
		description: ''
	});
	const sexOptions = ref([{
			id: 0,
			name: '女'
		},
		{
			id: 1,
			name: '男'
		}
	]);

	const myhospitals = ref([]);

	onMounted(() => {
		fetchEscortInfo();
		// 获取医院列表
		myrequest({
			myurl: '/hospitalInfo/list',
			method: 'GET',
			mysuccess: (res) => {
				myhospitals.value = res.data;
			}
		});
	});

	// 医院选择处理
	const handleHospitalChange = (e) => {
		const selectedIndex = e.detail.value;
		formData.value.hospitalId = myhospitals.value[selectedIndex]?.id || '';
	};
	const avatarUrl = ref('');
	const filesUrls = ref([]);
	const tempFilePaths = ref([]);

	// 选择头像
	const chooseAvatar = () => {
		uni.chooseImage({
			count: 1, // 默认9
			sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
			sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
			success: function(res) {
				const filePaths = res.tempFilePaths;
				avatarUrl.value = filePaths[0];
				tempFilePaths.value.avatar = filePaths[0];
			}
		});
	};

	// 选择个性化描述图片
	const chooseFiles = () => {
		uni.chooseImage({
			count: 9, // 最多可以选择的图片张数
			sizeType: ['original', 'compressed'],
			sourceType: ['album', 'camera'],
			success: function(res) {
				const filePaths = res.tempFilePaths;
				filesUrls.value = [...filesUrls.value, ...filePaths];
				tempFilePaths.value.files = tempFilePaths.value.files ? [...tempFilePaths.value.files, ...
					filePaths
				] : [...filePaths];
			}
		});
	};

	const handleModal = () => {
		showModal.value = true;
	}

	const fetchEscortInfo = () => {
		myrequest({
			myurl: '/become/escort/info',
			method: 'GET',
			header: {
				'Authorization': token,
				'Source-Platform': 'mini-program'
			},
			mysuccess: (res) => {
				escortInfo.value = res.data;
			}
		});
	};

	const cancelEscort = (id) => {
		// 调用取消接口
		myrequest({
			myurl: `/become/escort/cancel?id=${id}`,
			method: 'GET',
			header: {
				'Authorization': token,
				'Source-Platform': 'mini-program'
			},
			mysuccess: (res) => {
				fetchEscortInfo(); // 刷新信息
			}
		});
	};

	const handleSubmit = async () => {
		if (!avatarUrl.value || filesUrls.value.length === 0) {
			uni.showToast({
				title: '请上传头像和描述图片',
				icon: 'none'
			});
			return;
		}

		const allFilePaths = [tempFilePaths.value.avatar, ...(Array.isArray(tempFilePaths.value.files) ?
			tempFilePaths.value.files : [])];
		console.log("上传的图片个数：", allFilePaths.length); // 应该输出正确的图片数量

		// 上传所有文件
		// 修改后的上传方法示例
		const uploadPromises = allFilePaths.map((filePath) => {
			return new Promise((resolve, reject) => {
				uni.uploadFile({
					// url: 'http://47.98.201.46:18080/common/upload',
					url: 'http://192.168.1.160:18080/common/upload',
					filePath: filePath,
					name: 'files', // 关键修正：参数名需与后端@RequestParam名称一致
					header: {
						'Authorization': token,
						'Source-Platform': 'mini-program'
					},
					success: (res) => {
						if (res.statusCode === 200) {
							try {
								const response = JSON.parse(res.data);
								if (response.code === 200) {
									resolve(response.data[
										0
									]); // 假设返回结构为{"code":200,"data":["url1","url2"]}
								} else {
									reject(new Error(response.message));
								}
							} catch (e) {
								reject(new Error('响应解析失败'));
							}
						} else {
							reject(new Error(`上传失败，状态码：${res.statusCode}`));
						}
					},
					fail: (err) => reject(err)
				});
			});
		});

		let uploadedUrls;
		try {
			uploadedUrls = await Promise.all(uploadPromises);
		} catch (error) {
			uni.showToast({
				title: '文件上传失败',
				icon: 'none'
			});
			console.error('文件上传错误:', error);
			return;
		}

		// 分离头像URL和其他文件URL
		const avatarUrlUploaded = uploadedUrls[0];
		const filesUrlsUploaded = uploadedUrls.slice(1);

		// 最终提交数据结构
		const finalFormData = {
			...formData.value,
			hospitalId: formData.value.hospitalId, // 已处理为实际ID
			avatar: avatarUrlUploaded,
			files: filesUrlsUploaded
		};

		// 提交表单数据
		myrequest({
			myurl: '/user/save',
			method: 'POST',
			data: finalFormData,
			header: {
				'Authorization': token,
				'Source-Platform': 'mini-program',
				'Content-Type': 'application/json'
			},
			mysuccess: (res) => {
				console.log("提交成功", res);
				uni.showToast({
					title: '提交成功'
				});
				showModal.value = false;
				resetFormData();
				fetchEscortInfo();
			},
			myfail: (error) => {
				console.error("提交失败", error);
				uni.showToast({
					title: '提交失败',
					icon: 'none'
				});
			}
		});
	};

	const handleSexChange = (e) => {
		formData.value.sex = e.detail.value;
	};

	const resetFormData = () => {
		formData.value = {
			name: '',
			age: '',
			sex: 0,
			phone: '',
			identityCard: '',
			hospitalId: '',
			addressInfo: '',
			description: ''
		};
		avatarUrl.value = '';
		filesUrls.value = [];
		tempFilePaths.value = {};
	};
</script>

<style>
	/* 在原有样式基础上添加 */
	.upload-preview {
		display: flex;
		flex-wrap: wrap;
		margin: 10rpx 0;
	}

	.upload-preview image {
		width: 120rpx;
		height: 120rpx;
		margin: 5rpx;
		border-radius: 8rpx;
	}

	.container {
		padding: 20rpx;
		height: 100vh;
		display: flex;
		flex-direction: column;
	}

	.detail-container {
		flex: 1;
		padding: 20rpx;
	}

	.weui-cell {
		display: flex;
		align-items: center;
		padding: 15rpx;
		border-bottom: 1px solid #eaeaea;
	}

	.weui-cell__hd {
		margin-right: 10rpx;
	}

	.weui-cell__bd {
		flex: 1;
		font-size: 16px;
		color: #333;
	}

	.weui-cell__ft {
		font-size: 14px;
		color: #999;
	}

	.detail-item {
		margin-bottom: 20rpx;
		display: flex;
		align-items: center;
	}

	.detail-item label {
		width: 120rpx;
		font-weight: bold;
	}

	.detail-item text {
		flex: 1;
	}

	.fixed-bottom {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		background-color: #fff;
		text-align: center;
		padding: 20rpx 0;
		box-shadow: 0 -2rpx 4rpx rgba(0, 0, 0, 0.1);
		z-index: 10;
	}

	.apply-button {
		width: 80%;
		margin: 0 auto;
		background-color: #0BB584;
		color: #fff;
		border: none;
		padding: 20rpx;
		font-size: 28rpx;
		border-radius: 10rpx;
	}

	.modal-overlay {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background-color: rgba(0, 0, 0, 0.5);
		display: flex;
		justify-content: center;
		align-items: center;
		z-index: 20;
	}

	.modal-content {
		background-color: #fff;
		padding: 40rpx;
		border-radius: 20rpx;
		width: 80%;
		max-height: 80%;
		display: flex;
		flex-direction: column;
		overflow-y: auto;
	}

	.form-scroll {
		flex: 1;
		overflow-y: auto;
	}

	.form-item {
		margin-bottom: 20rpx;
	}

	.form-item label {
		display: block;
		margin-bottom: 10rpx;
		font-weight: bold;
	}

	.form-item input,
	.form-item textarea {
		width: 95%;
		padding: 10rpx;
		border: 1rpx solid #ccc;
		border-radius: 10rpx;
	}

	.modal-footer {
		display: flex;
		justify-content: space-between;
		margin-top: 20rpx;
		border: none;
	}

	.submit-button {
		width: 45%;
		background-color: #0BB584;
		color: #fff;
		border: none;
		font-size: 32rpx;
		border-radius: 10rpx;
	}

	.cancel-button {
		background-color: #0BB584;
		color: #fff;
		border: none;
		font-size: 32rpx;
		border-radius: 10rpx;
	}
</style>